package a66weding.com.jiehuntong.view;

import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;

import a66weding.com.jiehuntong.R;

/**
 * @version :
 * @creator : AxDu
 * @create-time : 2016/5/18
 * @description :
 */
public class EditTextWithAutoClear2 extends EditText implements View.OnFocusChangeListener  {
    private Drawable clearBtn; //输入框右侧的删除按钮

    private boolean isFoucs; //控件焦点

    private Context context;

    public EditTextWithAutoClear2(Context context) {
        this(context, null);
        initial();
    }

    public EditTextWithAutoClear2(Context context, AttributeSet attrs) {
        this(context, attrs, android.R.attr.editTextStyle);
        initial();
    }

    public EditTextWithAutoClear2(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context=context;
        initial();
    }

    private void initial() {
        clearBtn = getCompoundDrawables()[2]; //EditText右侧的删除图标
        if (clearBtn == null)
            clearBtn = getResources().getDrawable(R.mipmap.title_bar_search_button_clear_background);

        clearBtn.setBounds(0, 0, clearBtn.getIntrinsicWidth(), clearBtn.getIntrinsicHeight());

        clearText(false); //默认设置隐藏图标

    }



    protected void clearText(boolean visible) {
        //开始写代码。实现设置清除图标的显示与隐藏。绘制到EditText上
        Drawable right =clearBtn;
        if(visible && length()>0) {
            setCompoundDrawables(null, null, right, null);
        }
    }



    @Override
    public void onFocusChange(View view, boolean b) {
        this.isFoucs = b;
        if (isFoucs)
            clearText(getText().length() > 0);
        else
            clearText(false);
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {

            if (clearBtn != null && event.getAction() == MotionEvent.ACTION_UP) {
                int eventX = (int) event.getRawX();
                int eventY = (int) event.getRawY();
                Log.e("Log", "eventX = " + eventX + "; eventY = " + eventY);
                Rect rect = new Rect();
                getGlobalVisibleRect(rect);
                rect.left = rect.right - 50;
                if(rect.contains(eventX, eventY))
                    setText("");
                clearText(false);
            }

        }
        return super.onTouchEvent(event);
    }
















}
